<template>
	<el-container v-if="isAlready">
		<el-header>
			<div class="left-panel">
				<fsButton ref="button" plain size="default" :buttons="buttons" @clickHandler="buttonHandler"></fsButton>
			</div>
			<div class="right-panel">
				<ex-search ref="search" :searches="searches" @searchOk="searchHandler" default-code="code" placeholder="请输入单据编码" :fixedParam="fixedParams" :initParams="searchParams"></ex-search>
			</div>
		</el-header>
		<el-main class="nopadding">
			<ex-table id="checkTaskTable" ref="table" :tablename="title" :columns="columns" :url="this.$API.asset.document.list.url" :refs="this.$refs" :params="{manageDeptIds:this.manageDeptIds}" search="search" @columnClick="columnClickHandler"></ex-table>
		</el-main>
	</el-container>
	<data-card ref="dataCard"></data-card>
	<el-dialog
		v-model="compelDialogVisible"
		title="同意审批"
		width="400">
		<template #header="{ titleClass }">
			<div class="el-dialog_bottomClass">
				<span :class="titleClass">同意审批</span>
			</div>
		</template>
		<el-form :model="formDatas" ref="dialogForm" :rules="button_rules">
			<el-form-item label="评论" prop="comment">
				<el-input :rows="3"  v-model="formDatas.comment" clearable type="textarea" placeholder="请输入评论" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="el-dialog_headerClass">
				<el-button class="margin-topClass" @click="commentCancel">取 消</el-button>
				<el-button class="margin-topClass" type="primary" @click="commentApprove">确 定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script>
import ExTable from "@/components/exTable/index.vue";
import ExSearch from "@/components/exSearch/index.vue";
import ExTreeNavigation from "@/components/exSearchTree/index.vue";
import ExSearchTree from "@/components/exSearchTree/index.vue";
import scSelectFilter from "@/components/scSelectFilter/index.vue";
import tool from "@/utils/tool";
import DataCard from "@/views/asset/card/card.vue";
import {DOCUMENT_STATUS} from "@/utils/StaticConstant";
import useTabs from "@/utils/useTabs";
import formRule from "@/utils/formRule";
import BaseTemplate from "@/utils/baseTemplate";
export default {
	name: '单据查询',
	components: {
		DataCard,
		scSelectFilter,
		ExSearchTree,
		ExTreeNavigation,
		ExSearch,
		ExTable,
	},
	data() {
		return {
			dialog: {
				save: false,
				permission: false,
			},
			apiObj: [],
			buttons: [
				{name: "导出", icon: "el-icon-download", click: "export", type: "info", permission: "export"},
				{name: this.$t('button.delete'), icon: "el-icon-delete", click: "del", type: "info",permission: "delete"},
				{name: "作废", icon: "el-icon-edit", click: "cancel", type: "info",permission: "cancel"},
				{name: "强制作废", icon: "el-icon-edit", click: "compelCancel", type: "info",permission: "compelCancel"},
				{name: "强制同意", icon: "el-icon-edit", click: "compelApprove", type: "info",permission: "compelApprove"},
				{name: "重新推送", icon: "el-icon-edit", click: "restPush", type: "info",permission: "restPush"},
				{name: "重新同步", icon: "el-icon-edit", click: "rePass", type: "info",permission: "rePass"},
			],
			searches: [
				{type: "input", name: "单据编码", code: "code", placeholder: "请输入编码", maxlength: 30, showLimit: true},
				{type: "tree-select", name: "单据类型", code: "queryDocumentConfigIds", placeholder: "请选择单据类型", dictCode:'FamsDocumentConfig',checkStrictly:true,multiple:true,dataPermissionProcess:true},
				{type: "daterange", name: "制单日期", code: "createTimeStart,createTimeEnd", placeholder: "请选择制单日期", formatter:"YYYY-MM-dd",valueFormat:"YYYYMMDD",range:365},
				{type: "tree-select", name: "制单部门", code: "createOrganizationIds", placeholder: "请选择制单部门", dictCode:'SysOrganization',priKey:true,checkStrictly:true,multiple:true,dataPermissionProcess:true,permissionData:this.$TOOL.current.readDeptIds()},
				{type: "selector", name: "制单人", code: "createUser", placeholder: "请选择制单人", dictCode:'SysUser',priKey:true},
				{type: "select", name: "单据状态", code: "statusList", placeholder: "请选择单据状态", dictCode:'DOCUMENT_STATUS',multiple:true},
				{type: "select", name: "审批状态", code: "approveStatus", placeholder: "请选择审批状态", dictCode:'AUDIT_STATUS'},
				{type: "input", name: "申购单号", code: "other.purchaseOrderCode", placeholder: "请输入申购单号"},
			],
			columns: [
				{code: "status", name: "单据状态", width:"90",sortable: true,formatter:"DICT",key: "DOCUMENT_STATUS"},
				{code: "code", name: "单据编码", width:"130",click:"show",sortable:true},
				{code: "createUser", name: "制单人", width:"110",formatter: "DICT",key: "SysUser"},
				{code: "createOrganizationId", name: "制单部门", width:"",formatter: "DICT",key: "SysOrganization"},
				{code: "documentConfigId", name: "单据名称", width:"120",formatter:"DICT",key: "FamsDocumentConfig"},
				{code: "processTypeId", name: "处理方式", width:"120",formatter: "DICT",key: "FamsDocumentProcessType"},
				{code: "other.auditStatus", name: "审批状态", width:"80",formatter: "DICT",key: "AUDIT_STATUS"},
				{code: "other.purchaseOrderCode", name: "申购单号"},
				{code: "createTime", name: "制单时间", width:"170",sortable:true,formatter: "DATETIME"},
			],
			button_rules: {
				comment: [{required: true, message: "请输入评论", trigger: "blur"},],
			},
			parentLevelCode:"",
			assetIds:[],
			isAlready:false,
			compelDialogVisible:false,
			searchParams:{},
			fixedParams:{
			},
			formDatas: {},
			statusList: [],
			manageDeptIds:this.$TOOL.current.readDeptIds(),
			loading: false,
			loginUsers: tool.current.user(),
			title:"单据查询"
		}
	},
	created() {
		//如果是通过跳转过来的，标签的名称设置为跳转后的标题
		let routeParams = this.$store.state.routeParams[this.$route.params.key];
		if(routeParams){
			if(routeParams.title){
				useTabs.setTitle(routeParams.title);
				document.title = routeParams.title;
				this.title=routeParams.title;
			}
			if (routeParams.fixedParams) {
				Object.assign(this.fixedParams,routeParams.fixedParams);
			}
			if (routeParams.searchParams) {
				Object.assign(this.searchParams,routeParams.searchParams);
			}
			if(routeParams.queryType){
				this.buttons = [
					{name: "导出", icon: "el-icon-download", click: "export", type: "info"},
				]
			}else{
				this.buttons = [
					{name: "导出", icon: "el-icon-download", click: "export", type: "info"},
				]
			}
		}
		this.isAlready = true;
	},
	mounted() {
		try {
			if(this.fixedParams.manageDeptIds){
				this.manageDeptIds = this.fixedParams.manageDeptIds;
				this.searches.forEach(item=>{
					if(item.code==='createOrganizationIds'){
						item.permissionData = this.manageDeptIds;
					}
				})
			}
			if(this.fixedParams.statusList){
				this.statusList = this.fixedParams.statusList;
				this.searches.forEach(item=>{
					if(item.code==='statusList'){
						item.permissionData = this.statusList;
					}
				})
			}
			if(this.searchParams.queryDocumentConfigIds){
				this.queryDocumentConfigIds = this.searchParams.queryDocumentConfigIds;
				this.searches.forEach(item=>{
					if(item.code==='queryDocumentConfigIds'){
						item.permissionData = this.queryDocumentConfigIds;
					}
				})
			}
			this.isAlready = true;
		} catch (err) {
			this.$message.error(this.$t('common.config_error'));
			useTabs.close();
		}
	},
	beforeMount() {

	},
	methods: {
		buttonHandler(index, name) {
			this.$options.methods[name](this, index);
		},
		async searchTreeHandler(data) {
			let queryParams = {pathCode:data.levelCode}
			this.parentLevelCode= data.levelCode;
			await this.$refs.table.refresh(queryParams);
		},

		async searchHandler() {
			let queryParams = {pathCode: this.parentLevelCode}
			await this.$refs.table.refresh(queryParams);
		},
		columnClickHandler(name,data){
			this.$options.methods[name](this, data);
		},
		//查看
		show(_this,row) {
			_this.$nextTick(() => {
				_this.$router.push({name:"documentPrepare",params:{fromRouteId:_this.$TOOL.crypto.MD5(_this.$route.path),configId:row.documentConfigId,id:row.id}});
			})
		},
		//批量删除
		del(_this, index) {
			let selections = _this.$refs.table.selections();
			if (selections.length === 0) {
				_this.$message.warning(_this.$t("请选择需要删除的制单中的单据"));
				return;
			}
			let delarray = [];
			for (let index = 0; index < selections.length; index++) {
				const element = selections[index];
				if(element.status === DOCUMENT_STATUS.PREPARING){
					delarray.push(element.id);
				}
			}
			if (delarray.length === 0) {
				_this.$message.warning(_this.$t("请选择需要删除的制单中的单据"));
				return;
			}
			_this.$confirm(`确定删除选中的 ${selections.length} 单据信息吗？`, '警告', {
				type: 'warning'
			}).then(async () => {
				_this.dialogVisible = true;
				_this.$refs.button.loading(index, true);
				var res = await _this.$API.asset.document.deleteByIds.post(delarray);
				if (res.code === 2000) {
					_this.$message.success(_this.$t("code."+res.code));
					useTabs.refresh();
					_this.$store.dispatch("commit",selections[0].entityName);
				}
				_this.$refs.button.loading(index, false);
			}).catch(() => {
				_this.$refs.button.loading(index, false);
			});
		},
		//作废
		async cancel(_this, index) {
			let selections = _this.$refs.table.selections();
			// if (selections.length === 0) {
			// 	_this.$message.warning(_this.$t("common.please_select_data"));
			// 	return;
			// }
			if (selections.length !== 1) {
				_this.$message.warning("请选择需要作废的一条单据数据");
				return;
			}
			let delarray = [];
			for (let index = 0; index < selections.length; index++) {
				const element = selections[index];
				delarray.push(element.id);
				if(element.status!==DOCUMENT_STATUS.REVIEW){
					_this.$message.error("只有审核中的单据才允许作废");
					return;
				}
				if(element.other.notCancel){
					_this.$message.error("对外接口异常的单据无法作废");
					return;
				}
			}
			_this.$confirm(`确定作废选中的 ${selections.length} 项的单据吗？`, '警告', {
				type: 'warning'
			}).then(async () => {
				_this.$refs.button.loading(index, true);
				let parms = {};
				parms.ids = delarray;
				var res = await _this.$API.asset.document.cancelByIds.post(parms);
				if (res.code === 2000) {
					_this.$message.success(_this.$t("code."+res.code));
					_this.searchHandler();
					_this.$store.dispatch("commit",selections[0].entityName);
					_this.$refs.button.loading(index, false);
				}else {
					_this.$refs.button.loading(index, false);
				}
			}).catch(() => {
				_this.$refs.button.loading(index, false);
			});
		},
		//强制作废
		async compelCancel(_this, index) {
			let selections = _this.$refs.table.selections();
			if (selections.length !== 1) {
				_this.$message.warning("请选择需要强制作废的一条数据");
				return;
			}
			let delarray = [];
			for (let index = 0; index < selections.length; index++) {
				const element = selections[index];
				delarray.push(element.id);
				if(element.status!==DOCUMENT_STATUS.REVIEW){
					_this.$message.error("只有审核中的才允许强制作废");
					return;
				}
			}
			_this.$confirm(`确定强制作废选中的 ${selections.length} 项吗？`, '警告', {
				type: 'warning'
			}).then(async () => {
				_this.$refs.button.loading(index, true);
				let parms = {};
				parms.ids = delarray;
				var res = await _this.$API.asset.document.compelCancelByIds.post(parms);
				if (res.code === 2000) {
					_this.$message.success(_this.$t("code."+res.code));
					_this.searchHandler();
					_this.$store.dispatch("commit",selections[0].entityName);
					_this.$refs.button.loading(index, false);
				}else {
					_this.$refs.button.loading(index, false);
				}
			}).catch(() => {
				_this.$refs.button.loading(index, false);
			});
		},
		//强制同意
		async compelApprove(_this, index) {
			let selections = _this.$refs.table.selections();
			if (selections.length !== 1) {
				_this.$message.warning("请选择需要强制同意的一条数据");
				return;
			}
			let delarray = [];
			for (let index = 0; index < selections.length; index++) {
				const element = selections[index];
				delarray.push(element.id);
				if(element.status!==DOCUMENT_STATUS.REVIEW){
					_this.$message.error("只有审核中的才允许作废");
					return;
				}
			}
			_this.compelDialogVisible = true;
			_this.formDatas.ids = delarray;
			_this.formDatas.index = index;
			console.log(_this.formDatas)
			_this.formDatas.entityName = selections[0].entityName;

		},
		//关闭评论
		commentCancel(){
			this.formDatas = {};
			this.compelDialogVisible = false;
		},
		//评论提交
		async commentApprove() {
			let valid = await this.$refs.dialogForm.validate(valid => {
				return valid;
			});
			if (valid) {
				this.$confirm(`确定强制同意选中的1项吗？`, '警告', {
					type: 'warning'
				}).then(async () => {
					let parms = {};
					parms.ids = this.formDatas.ids;
					parms.name = this.formDatas.comment;
					let index = this.formDatas.index;
					this.$refs.button.loading(index, true);
					this.compelDialogVisible = false;
					let entityName = this.formDatas.entityName;
					var res = await this.$API.asset.document.compelApproveByIds.post(parms);
					if (res.code === 2000) {
						this.$message.success(this.$t("code." + res.code));
						this.searchHandler();
						this.$store.dispatch("commit", entityName);
						this.$refs.button.loading(index, false);
					} else {
						this.$refs.button.loading(index, false);
					}
				}).catch(() => {
					this.$refs.button.loading(index, false);
				});
			}
		},
		//重新同步
		async rePass(_this, index) {
			let selections = _this.$refs.table.selections();
			if (selections.length !== 1) {
				_this.$message.warning("只能重新同步一条单据数据");
				return;
			}
			let delarray = [];
			for (let index = 0; index < selections.length; index++) {
				const element = selections[index];
				delarray.push(element.id);
			}
			_this.$confirm(`确定重新同步选中的 ${selections.length} 项单据吗？`, '警告', {
				type: 'warning'
			}).then(async () => {
				_this.$refs.button.loading(index, true);
				let parms = {};
				parms.id = delarray[0];
				var res = await _this.$API.asset.document.rePass.post(parms);
				if (res.code === 2000) {
					_this.$message.success(_this.$t("code."+res.code));
					_this.searchHandler();
					_this.$store.dispatch("commit",selections[0].entityName);
					_this.$refs.button.loading(index, false);
				}else {
					_this.$refs.button.loading(index, false);
				}
			}).catch(() => {
				_this.$refs.button.loading(index, false);
			});
		},

    //重新推送
    async restPush(_this, index) {
      let selections = _this.$refs.table.selections();
      if (selections.length !== 1) {
        _this.$message.warning("请选择需要重新推送的一条数据");
        return;
      }
      let delarray = [];
      for (let index = 0; index < selections.length; index++) {
        const element = selections[index];
        delarray.push(element.id);
        if(element.status!==DOCUMENT_STATUS.REVIEW){
          _this.$message.error("只有审核中的单据才允许重新推送");
          return;
        }
        if(!element.other.notCancel){
          _this.$message.error("只有对外接口的单据才能重新推送");
          return;
        }
      }
      _this.$confirm(`确定重新推送选中的 ${selections.length} 项单据吗？`, '警告', {
        type: 'warning'
      }).then(async () => {
        _this.$refs.button.loading(index, true);
        let parms = {};
        parms.ids = delarray;
        var res = await _this.$API.asset.document.restPush.post(parms);
        if (res.code === 2000) {
          _this.$message.success(_this.$t("code."+res.code));
          _this.searchHandler();
          _this.$store.dispatch("commit",selections[0].entityName);
          _this.$refs.button.loading(index, false);
        }else {
          _this.$refs.button.loading(index, false);
        }
      }).catch(() => {
        _this.$refs.button.loading(index, false);
      });
    },

		//导出
		async export(_this,index) {
      let attachParams = {};
      attachParams.exportType = "queryExport";
      let exportApi = _this.$API.asset.document.export;
      let exTableRef = _this.$refs.table;
      let exportBtnRef = _this.$refs.button;
      let exportBtnIndex = index;
      await BaseTemplate.export(_this, exportApi, attachParams, exportBtnRef, exportBtnIndex, exTableRef);
		},
	}
}

</script>
<style scoped>
.el-dialog_headerClass {
	border-top: 1px solid #e9e9e9;
}
.el-dialog_bottomClass {
	border-bottom: 1px solid #e9e9e9;
}
.margin-topClass {
	margin-top: 5px;
}
</style>
